const api = require('../../utils/request.js');
const Cart = require('../../utils/cart.js');

Page({
  data: {
    // 店铺列表
    stores: [{
        id: 1,
        name: '永胜炸鸡（三原南五巷店）',
        address: '上海市黄浦区人民大道123号',
        image: '/static/images/store1.jpeg', // 店铺图片
        status: '营业中'
      },
      {
        id: 2,
        name: '永胜炸鸡（渭南红化店）',
        address: '上海市浦东新区陆家嘴环路456号',
        image: '/static/images/store1.jpeg', // 店铺图片
        status: '营业中'
      }
    ],
    currentStoreIndex: 0, // 默认选择第一家店铺
    currentStore: {
      id: 1,
      name: '永胜炸鸡（三原南五巷店）',
      address: '上海市黄浦区人民大道123号',
      image: '/static/images/store1.jpeg', // 店铺图片
      status: '营业中'
    },
    categories: [{
        id: 0,
        name: '全部'
      },
      {
        id: 1,
        name: '炸鸡类'
      },
      {
        id: 2,
        name: '小吃类'
      },
      {
        id: 3,
        name: '饮料类'
      },
      {
        id: 4,
        name: '套餐类'
      }
    ],
    currentCategory: 0,
    products: [],
    cartTotalQuantity: 0,
    pickupMode: '自取', // 新增：自取/外卖
    banners: [
      { url: 'https://hidak.oss-cn-beijing.aliyuncs.com/banner4.png' },
      { url: 'https://hidak.oss-cn-beijing.aliyuncs.com/banner2.png' },
      { url: 'https://hidak.oss-cn-beijing.aliyuncs.com/banner3.png' }
    ],
  },
  // 切换展开/收起状态
  toggleExpand(e) {
    // debugger
    const index = e.currentTarget.dataset.index;
    const products = this.data.products;

    // 更新对应商品的展开状态
    products[index].expanded = !products[index].expanded;

    this.setData({
      products
    });
  },
  onLoad() {
    this.setData({
      currentStore: this.data.stores[0]
    });
    this.loadCategories();
    this.loadProducts();
    this.updateCartQuantity();
  },

  async loadCategories() {
    try {
      const api = require('../../utils/request.js');
      const result = await api.getCategories();
      
      if (result.code === 200 && result.data) {
        // 添加"全部"选项
        const categories = [
          { id: 0, name: '全部' },
          ...result.data
        ];
        
        this.setData({
          categories: categories
        });
      }
    } catch (error) {
      console.error('加载分类失败:', error);
    }
  },

  onShow() {
    this.updateCartQuantity();
  },

  // 显示店铺选择器
  showStorePicker() {
    const storeNames = this.data.stores.map(store => store.name);

    wx.showActionSheet({
      itemList: storeNames,
      success: (res) => {
        const selectedIndex = res.tapIndex;
        this.setData({
          currentStoreIndex: selectedIndex,
          currentStore: this.data.stores[selectedIndex]
        });
      }
    });

  },
  loadProductsByStore(storeId) {
    // 调用API加载对应店铺的商品
    // this.setData({ products: newProducts });
  },

  async loadProducts() {
    try {
      wx.showLoading({
        title: '加载中...'
      });

      let result;
      if (this.data.currentCategory === 0) {
        result = await api.getProducts();
      } else {
        result = await api.getProductsByCategory(this.data.currentCategory);
      }

      // 处理后端返回的ResultVO格式，提取data字段
      const products = result.data || [];
      
      this.setData({
        products: products
      });
    } catch (error) {
      console.error('加载商品失败:', error);
      wx.showToast({
        title: '加载商品失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  switchCategory(e) {
    const categoryId = e.currentTarget.dataset.id;
    if (this.data.currentCategory !== categoryId) {
      this.setData({
        currentCategory: categoryId
      });
      this.loadProducts();
    }
  },

  updateCartQuantity() {
    this.setData({
      cartTotalQuantity: Cart.getTotalQuantity()
    });
  },

  addToCart(e) {
    const product = e.currentTarget.dataset.item;
    Cart.addToCart(product);
    this.updateCartQuantity();
    wx.showToast({
      title: '已加入购物车',
      icon: 'success',
      duration: 1500
    });
  },

  goToProductDetail(e) {
    const productId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/product/product?id=${productId}`
    });
  },

  goToCart() {
    wx.navigateTo({
      url: '/pages/cart/cart'
    });
  },

  // 配送方式切换
  switchPickupMode(e) {
    const mode = e.currentTarget.dataset.mode;
    if (this.data.pickupMode !== mode) {
      this.setData({ pickupMode: mode });
    }
  },

  // 选规格弹窗（预留）
  selectSpec(e) {
    const product = e.currentTarget.dataset.item;
    wx.showToast({
      title: '规格选择弹窗待实现',
      icon: 'none'
    });
    // TODO: 打开规格选择弹窗
  },
});